<template>
  <div p-30px>
    <h2>角色管理</h2>

    <!-- 按钮 -->
    <el-button @click="hanleAddRole">角色添加</el-button>

    <!-- 表格 -->
    <el-table :data="roles" style="width: 100%">
      <el-table-column prop="id" label="角色id" width="180" />
      <el-table-column prop="name" label="角色名称" width="180" />
      <el-table-column prop="description" label="描述" />
      <el-table-column
        prop="is_default"
        label=" 默认角色"
        :formatter="formatter"
      />
      <el-table-column label="操作" fixed="right">
        <template #default="scope">
          <el-button link @click="handleRoleMenu(scope.row)"
            >菜单权限</el-button
          >
          <el-button link @click="handleEditRole(scope.row)">编辑</el-button>
          <el-button link @click="handleRemove(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      :page-sizes="[1, 5, 10, 20]"
      layout="prev, pager, next, sizes, total"
      :total="count"
      :page-size="pageSize"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
    <!-- 抽屉组件 -->
    <right-panel v-model="visible" :title="panelTitle">
      <!-- 表单组件 -->
      <editor-role
        :type="editType"
        :data="editData"
        @submit="handleSubmit"
      ></editor-role>
    </right-panel>
    <!-- 权限弹窗 -->
    <role-menu
      :role="roleData"
      v-model="roleMenuVisible"
      v-if="roleMenuVisible && roleData"
    />
  </div>
</template>
<script lang="ts" setup>
import type { IRole } from "@/api/role"
import { useRoleStore } from "@/stores/role"
import EditorRole from "./components/editor-role.vue"
import { useRoleHelpers } from "./roleHelpers"
const store = useRoleStore()
const pageNum = ref(0)
const pageSize = ref(10)
const {
  handleSubmit,
  handleRemove,
  handleEditRole,
  hanleAddRole,
  panelTitle, //
  editType,
  visible,
  editData
} = useRoleHelpers({ pageNum, pageSize })
const { count, roles } = toRefs(store.state)
watchEffect(() => {
  store.getRoles({ pageNum: pageNum.value, pageSize: pageSize.value })
})
const handleSizeChange = (val: number) => {
  pageSize.value = val
}
const handleCurrentChange = (val: number) => {
  pageNum.value = val - 1
}
const formatter = (row: IRole) => {
  return row.is_default ? "是" : "否"
}
// 权限要编辑的角色
const roleData = ref<IRole | null>(null)
// 权限弹窗
const roleMenuVisible = ref(false)
const handleRoleMenu = (row: IRole) => {
  roleMenuVisible.value = true
  roleData.value = row
}
</script>
